#!/usr/bin/env python
import itertools
import cherrypy
import os
import threading
import random
import time
import fileinput
import  json
from AccuracyWeight import AccuracyWeight
from HybridWeight import HybridWeight
from OneMarkov import OneMarkov
        
        
class server(object):
    def __init__(self):
        self.thread1 = myThread()
        self.thread1.start()
        
    def datajson(self):
        result="{\"accuracy\":"+"\""+self.thread1.getAccuracy()+"\",\"coverage\":"+"\""+self.thread1.getCoverage()+"\",\"session\":"+"\""+self.thread1.getPartialSession()+"\",\"recommendation\":"+"\""+self.thread1.getRecommendationList()+"\",\"correct\":"+"\""+self.thread1.getCorrect()+"\",\"actual\":"+"\""+self.thread1.getActual()+"\",\"accuracy_aw\":"+"\""+self.thread1.getAccuracy_aw()+"\",\"coverage_aw\":"+"\""+self.thread1.getCoverage_aw()+"\",\"recommendation_aw\":"+"\""+self.thread1.getRecommendationList_aw()+"\",\"correct_aw\":"+"\""+self.thread1.getCorrect_aw()+"\",\"accuracy_hw\":"+"\""+self.thread1.getAccuracy_hw()+"\",\"coverage_hw\":"+"\""+self.thread1.getCoverage_hw()+"\",\"recommendation_hw\":"+"\""+self.thread1.getRecommendationList_hw()+"\",\"correct_hw\":"+"\""+self.thread1.getCorrect_hw()+"\"}"
        self.thread1.semaphore.release()
        return result
    datajson.exposed = True

class myThread (threading.Thread):
    def __init__(self):
        self.accuracy = 0
        self.coverage=0
        self.no_of_request=0
        self.no_request=0
        self.markov_dic={}
        self.recomendation_list=[]
        self.recomendation_list_aw=[]
        self.recomendation_list_hw=[]
        self.count=0
        self.correct=-1
        self.actual=""
        self.patial_session=[]
        self.om= OneMarkov()
        self.aw=AccuracyWeight()
        self.denom=0
        self.hw=HybridWeight()
        self.results_aw=[100,0,0]
        self.results_hw=[100,0,0]
        self.semaphore = threading.Semaphore(1)
        threading.Thread.__init__(self)
        
    def run(self):
        om= OneMarkov()
        self.aw.train()
        self.hw.train()
        self.markov_dic=self.om.initial_train()
        line=""
        for line in fileinput.input(['D:\\test_d.csv']):
               try:
                    list2=[]
                    line2= line.strip().rstrip(',')
                    line3=line2.split(',')
                    length=len(line3)
                    if length==1:
                        continue
                    for i in range(0,length-1):
                        self.semaphore.acquire()
                        self.no_of_request+=1
                        self.patial_session=line3[0:i+1]
                        self.recomendation_list=self.om.recommend(line3[i],self.markov_dic)
                        len1=len(self.recomendation_list)
                        if len1==0:
                            self.no_request+=1
                        else :
                            self.count+=1
                            j=i+1
                            self.actual=line3[j]
                            results=self.om.evaluate(self.recomendation_list,self.actual,self.count,self.accuracy) 
                            self.accuracy=results[0] 
                            self.correct=results[2]
                            self.coverage=float(self.no_of_request-self.no_request)/float(self.no_of_request)*100
        
                        print "accuracy:", self.accuracy
                        print "coverage", self.coverage
                        print "count", self.count
                        print "correct", self.correct 
                        j=i+1
                        self.actual=line3[j]
                        
                        self.recomendation_list_aw=self.aw.recommend(self.patial_session)
                        self.results_aw=self.aw.evaluate(self.recomendation_list_aw,self.actual)
                        print "Support based average  ",self.getAccuracy_aw()
                        
                        self.recomendation_list_hw=self.hw.recommend(self.patial_session)
                        if len(self.recomendation_list_hw)>0:
                            self.denom+=1
                        self.results_hw=self.hw.evaluate(self.recomendation_list_hw,self.actual)
                        print "Hybrid weighting average  ",self.getAccuracy_hw()
                    self.markov_dic=self.om.train(line,self.markov_dic)
                    self.aw.continous_train(line)
                    self.hw.continous_train(line)   
               except:
                    continue
                     
 
                    
    def getAccuracy(self):
        return str((self.accuracy*100))
    def getCoverage(self):
        return str(self.coverage)
    def getPartialSession(self):
        rec_partial = ','.join(str(i) for i in self.patial_session)
        return str(rec_partial)
    def getRecommendationList(self):
        rec_string = ','.join(str(i) for i in self.recomendation_list)
        return str(rec_string)
    def getCorrect(self):
        return str(self.correct)
    def getActual(self):
        return str(self.actual)
    def getAccuracy_aw(self):
        return str(self.aw.getAccuracy())
    def getCoverage_aw(self):
        return str(self.aw.getCoverage())
    def getRecommendationList_aw(self):
        rec_string = ','.join(str(i) for i in self.recomendation_list_aw)
        return str(rec_string)
    def getCorrect_aw(self):
        return str(self.aw.getCorrect())
    def getAccuracy_hw(self):
        return str(self.hw.getAccuracy())
    def getCoverage_hw(self):
        cov=0
        if not self.count == 0:
            cov = float(self.denom)*100/float(self.count) 
        return str(cov) 
    def getRecommendationList_hw(self):
        rec_string = ','.join(str(i) for i in self.recomendation_list_hw)
        return str(rec_string)
    def getCorrect_hw(self):
        return str(self.hw.getCorrect())

PATH = os.path.abspath(os.path.dirname("D:\\trunk\\src\\com\\irec\\UI\\"))
class Root(object): pass


cherrypy.tree.mount(Root(), '/', config={
        '/': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': PATH,
                'tools.staticdir.index': 'index.html',
            },
    })

cherrypy.tree.mount(server(),'/ajax')
cherrypy.engine.start()
cherrypy.engine.block()